<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-07-13
 * Time: 10:35
 */

namespace app\api\service\goods;


use app\api\model\GoodsOrder;
use app\api\model\User;
use app\api\service\Token;
use app\lib\exception\ParameterException;

class RefundOrderSer extends Token
{
    /**
     * 1.获取当前用户信息
     * 2.获取订单信息
     * 3.判断订单信息
     * 4.修改订单状态
     */

    // 用户信息
    private $user;

    // 订单信息
    private $order;

    function __construct($orderId)
    {
        $this->user = User::get(self::getCurrentUid());
        $this->order = GoodsOrder::get($orderId);
    }


    // 入口方法
    public function entrance()
    {
        return $this->judgeOrder();
    }

    // 判断订单
    private function judgeOrder()
    {
        if(!$this->order) {
            throw new ParameterException([
                'msg' => [
                    'goods' => '订单为空'
                ]
            ]);
        }
        if($this->order['user_id'] != $this->user['id']) {
            throw new ParameterException([
                'msg' => [
                    'goods' => '不属于您的订单'
                ]
            ]);
        }
        if($this->order['status'] == 1) {
            throw new ParameterException([
                'msg' => [
                    'goods' => '订单还未支付'
                ]
            ]);
        }
        if($this->order['status'] == 3) {
            throw new ParameterException([
                'msg' => [
                    'goods' => '订单已发货'
                ]
            ]);
        }
        if($this->order['status'] == 4) {
            throw new ParameterException([
                'msg' => [
                    'goods' => '订单已完成'
                ]
            ]);
        }
        if($this->order['status'] == 5) {
            throw new ParameterException([
                'msg' => [
                    'goods' => '退款请求已经申请'
                ]
            ]);
        }
        if($this->order['status'] == 6) {
            throw new ParameterException([
                'msg' => [
                    'goods' => '退款请求已经完成'
                ]
            ]);
        }
        return $this->updateOrder();
    }

    // 修改订单信息
    private function updateOrder()
    {
        GoodsOrder::where('id',$this->order['id'])->update([
            'status' => 5,
            'refund_status' => 2,
            'refund_time' => time(),
            'out_refund_no' => '1refund'.$this->order['id']
        ]);
        return writeJson(202, [], '申请成功！');
    }
}